// 导入工具类函数
const utils = require('../../../utils/util');
let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
const DBLibrary = db.collection('db_library');
let DBExam = db.collection('db_exam');
let DBScore = db.collection('db_score');
let times = 2 * 60 * 60;
let delay = null;
let dd = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    lists: [],
    msg: '开始考试',
    times: 0,
    arr: [], //用户的答案
    isStart: false,
    str: '00:00:00',
    dingshiqi: null,
    tip: '考试未开始',
    library_name: '',
    lib_id: '',
    type: '',
    duration: 0,
    current: 0,
    showContainer: true
  },
  changeFF(e){
    // console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    })
  },
  // 设置切换
  setHighLightFunc(e) {
    let current = e.currentTarget.dataset.current;
    console.log({
      current
    });
    this.setData({
      current
    })
  },

  // 点击提交试卷
  async submitExamFn() {
    if (delay != null) {
      clearTimeout(delay)
    }
    delay = setTimeout(async () => {
      let isStart = this.data.isStart;
      if (isStart) {
        let isAll = true;
        let arr = this.data.arr;

        for (let i = 0; i < arr.length; i++) {
          if (arr[i] == undefined) {
            isAll = false;
          }
        }

        if (arr.length != this.data.lists.length) {
          isAll = false;
        }
        // console.log(arr, {
        //   isAll
        // })
        if (isAll) {
          wx.showLoading({
            title: '正在统计分数',
            icon: 'none'
          })
          let nickName = wx.getStorageSync('nickName')
          let openid = wx.getStorageSync('openid')
          let s_total = 0;
          let s_wrong = 0;
          let s_right = 0;
          let s_times = this.data.duration - this.data.times
          let library_name = this.data.library_name
          let lib_id = this.data.lib_id;
          let type = this.data.type;
          // 统计分数
          if (arr.length == this.data.lists.length) {
            this.setData({
              // isStart: false,
              tip: '不能重复提交'
            })
            clearInterval(this.dingshiqi);
            let lists = this.data.lists;
            arr.forEach((row, index) => {
              if (row.myAnswer == lists[index].e_answer) {
                s_total += parseFloat(lists[index].e_score)
                s_right += 1;
              } else {
                s_wrong += 1;
              }
            })
            // 记录考试结果
            let s_id = Math.random().toString().slice(2)
            s_id = s_id + (new Date().getTime().toString().slice(-6))
            await DBScore.add({
              data: {
                nickName,
                openid,
                s_total,
                s_wrong,
                s_right,
                s_times,
                s_id,
                library_name,
                lib_id,
                create_time: new Date().getTime(),
                arr,
                type
              }
            }).then(
              content => {
                if (content.errMsg == "collection.add:ok") {
                  wx.showToast({
                    title: '添加成绩成功。',
                    icon: 'none'
                  })
                  wx.redirectTo({
                    // url: '../result/result?s_id='+s_id,
                    url: `../result/result?s_id=${s_id}&library_name=${library_name}`
                  })
                  wx.hideLoading();
                } else {
                  wx.showToast({
                    title: '添加成绩失败。',
                    icon: 'error'
                  })
                  wx.hideLoading();
                }
              }
            )


          } else {
            wx.showToast({
              title: '请不要漏题~',
              icon: 'none'
            })
          }

        } else {
          wx.showToast({
            title: '请不要漏题~',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: this.data.tip,
          icon: 'none'
        })
      }
      delay = null
    }, 500)
  },

  // 倒计时
  downTime() {
    // let times = this.data.times;
    let isStart = this.data.isStart;
    times--
    if (!isStart) {
      clearInterval(this.dingshiqi);
      return false;
    }
    if (times < 0) {
      clearInterval(this.dingshiqi);
      this.setData({
        isStart: false,
        tip: '考试已结束'
      })
      return false;
    }
    let h, m, s;
    h = Math.floor(times / 3600);
    m = Math.floor(times % 3600 / 60);
    s = Math.floor(times % 60);

    h = h < 10 ? '0' + h : '' + h;
    m = m < 10 ? '0' + m : '' + m;
    s = s < 10 ? '0' + s : '' + s;
    let str = `${h}:${m}:${s}`;
    this.setData({
      str,
      times
    });
  },
  // 点击开始
  startFn() {
    if (dd != null) {
      clearTimeout(dd);
    }
    let openid = wx.getStorageSync('openid')
    if (!openid) {
      wx.showToast({
        title: '请先登录再考试',
        icon: 'none'
      })
      return false;
    }
    dd = setTimeout(() => {
      this.setData({
        isStart: true
      })
      this.dingshiqi = setInterval(() => {
        this.downTime();
      }, 1000)
      this.downTime();
      dd = null;
    }, 300)
  },
  // 选择答案选项
  addAnswerFn(e) {
    let isStart = this.data.isStart;
    if (!isStart) {
      wx.showToast({
        title: '请点击开始考试',
        icon: 'none'
      })
      return false;
    }
    let index = e.currentTarget.dataset.index - 0;
    let id = e.currentTarget.dataset.id;
    let opt = e.currentTarget.dataset.opt;
    // console.log({index,id});
    let arr = this.data.arr;
    let lists = this.data.lists;
    // console.log(lists)
    let n = this.data.current;
    n++
    let current = n < lists.length - 1 ? n : lists.length - 1
    // let current = index
    if (opt) {
      if (lists[index]) {
        // console.log( lists[index].e_options[id].show)
        // index: 行
        // id: 列
        if (lists[index]['e_options']) {
          lists[index]['e_options'].forEach((item, j) => {
            lists[index]['e_options'][j].show = false;
          })
          lists[index]['e_options'][id].show = true;
          // console.log( lists[index]['e_options'][id].show)
          arr[index] = lists[index];
          lists[index].myAnswer = opt;
          lists[index].show = true;
          this.setData({
            lists,
            arr,
            current
          })
          // console.log('--->',arr)
        }
      }
    }
  },
  // 获取题目列表
  async getTopicList(lib_id) {
    let res = await DBExam.where({
      lib_id
    }).count()
    let count = res.total;
    let all = [];
    wx.showLoading({
      title: '正在加载试卷。',
    })
    for (let i = 0; i < count; i += 20) {
      await DBExam.where({
          lib_id
        }).skip(i).get()
        .then(
          content => {
            // console.log('1.0', content)
            let {
              data
            } = content;
            if (data.length != 0) {
              let arr = data.map((item, index) => {
                let obj = {
                  ...item
                }
                obj.show = false;
                obj.index = index;
                return obj;
              })
              all = all.concat(arr)
            }
          }
        )
    }
    this.setData({
      lists: all
    })
    wx.hideLoading();
  },

  // beforeleave() {
  //   if (this.data.showContainer) {
  //     console.log('test')
  //     this.setData({
  //       showContainer: false
  //     })
  //   }

  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    let formData = {};
    if (options['lib_id'] == undefined || options['type'] == undefined || options['library_name'] == undefined) {
      return false;
    }
    // 初始化
    formData['lib_id'] = options['lib_id'];
    formData['type'] = options['type'];
    formData['library_name'] = options['library_name'];

    if (options['library_duration']) {
      formData['library_duration'] = options['library_duration']
    }



    let {
      lib_id,
      type,
      library_name,
      library_duration
    } = formData

    let hours = parseFloat(library_duration) || 2;

    let times = hours * 60 * 60;
    let h, m, s;
    h = Math.floor(times / 3600);
    m = Math.floor(times % 3600 / 60);
    s = Math.floor(times % 60);

    h = h < 10 ? '0' + h : '' + h;
    m = m < 10 ? '0' + m : '' + m;
    s = s < 10 ? '0' + s : '' + s;
    let str = `${h}:${m}:${s}`;


    this.setData({
      lib_id,
      type,
      library_name,
      library_duration,
      times: hours * 60 * 60,
      duration: hours * 60 * 60,
      str
    })
    times = hours * 60 * 60
    // console.log({hours,times})
    this.getTopicList(lib_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // wx.showModal({
    //   title: '确定退出吗?',
    //   content: '',
    //   complete: (res) => {
    //     if (res.cancel) {
          
    //     }
    //     if (res.confirm) {
          
    //     }
    //   }
    // })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})